package com.javafactroy.kunlong.base.config.datasource.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import com.javafactroy.kunlong.base.config.datasource.DatasourceConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.mapper.autoconfigure.ConfigurationCustomizer;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;


@Configuration
@Slf4j
@Data
@Qualifier("mysqlDatasourceConfig")
@MapperScan(basePackages = {"com.javafactroy.kunlong.data.dao.mysql"}, sqlSessionTemplateRef = "mysqlSessionTemplate")
public class MysqlDatasourceConfig extends DatasourceConfig {
    protected static String[] MYBATIS_MAPPER_LOCATIONS = new String[]{"classpath*:/mapper/mysql/*.xml"};

    protected static String MYBATIS_BASE_PACKAGE = "com.javafactroy.kunlong.data.dao.mysql";


    @Qualifier("mysqlDataSource")
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    @Primary
    public DataSource mysqlDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();

        return druidDataSource;
    }

    @Bean("mysqlSessionTemplate")
    public SqlSessionTemplate buildSessionTemplate() throws Exception {
        return new SqlSessionTemplate(mysqlSessionFactory(mysqlDataSource()));
    }

    @Bean(name = "mysqlSessionFactroy")
    @Qualifier("mysqlSessionFactroy")
    public SqlSessionFactory mysqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<Resource> resList = new ArrayList<Resource>();
        for (String location : MYBATIS_MAPPER_LOCATIONS) {
            resList.addAll(Arrays.asList(resolver.getResources(location)));

        }
        bean.setMapperLocations(resList.toArray(new Resource[0]));
        //分页插件
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //分页数据库方言为mysql
        properties.setProperty("helperDialect", "mysql");
        //是否为分页数据库多个数据配置
        properties.setProperty("autoRuntimeDialect", "true");
        //是否分页合理化
        properties.setProperty("reasonable", "true");
        interceptor.setProperties(properties);
        bean.setPlugins(new Interceptor[] {interceptor});
        SqlSessionFactory sessionFactory = bean.getObject();
        sessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
        parse(dataSource);
        return sessionFactory;
    }


    @Bean(name = "mysqlTemplate")
    @Qualifier("mysqlTemplate")
    public JdbcTemplate mysqlTemplate(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
//	@Bean(name = "primaryMapperScannerConfigurer")
//	public MapperScannerConfigurer mapperScannerConfigurer() {
//		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//		mapperScannerConfigurer.setSqlSessionFactoryBeanName(SqlSessionFactory_NAME_PRIMARY);
//		mapperScannerConfigurer.setBasePackage(MYBATIS_BASE_PACKAGE);
//
//		return mapperScannerConfigurer;
//	}

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager(
            @Qualifier("mysqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 开启驼峰映射
     *
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}